import 'package:flutter/material.dart';

class LayoutBuilderTest extends StatefulWidget {
  const LayoutBuilderTest({Key? key}) : super(key: key);

  @override
  State<LayoutBuilderTest> createState() => _LayoutBuilderTestState();
}

class _LayoutBuilderTestState extends State<LayoutBuilderTest> {
  @override
  Widget build(BuildContext context) {
    List<Widget> _children = List.filled(7, Text('A'));
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('LayoutBuilder测试'),
        ),
        // column水平方向最大宽度为屏幕宽度
        body: Column(
          children: [
            SizedBox(width: 190, child: ResponsiveColumn(children: _children)),
            ResponsiveColumn(children: _children),
            Container(
              child: LayoutLogPrint<String>(
                child: Text('Hello'),
                tag: '子组件约束',
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class ResponsiveColumn extends StatelessWidget {
  final List<Widget> children;

  ResponsiveColumn({Key? key, required this.children}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (_, constraints) {
      if (constraints.maxWidth < 200) {
        return Column(children: children);
      }
      var _childern = <Widget>[];

      for (var i = 0; i < children.length; i += 2) {
        if (i + 1 < children.length) {
          _childern.add(Row(
            children: [children[i], children[i + 1]],
            mainAxisSize: MainAxisSize.min,
          ));
        } else {
          _childern.add(children[i]);
        }
      }
      return Column(
        children: _childern,
        mainAxisSize: MainAxisSize.min,
      );
    });
  }
}

/// 打印约束：布局时 父组件传递给子组件的约束
class LayoutLogPrint<T> extends StatelessWidget {
  final Widget child;
  final T? tag;
  const LayoutLogPrint({
    Key? key,
    required this.child,
    this.tag,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (_, constraints) {
      assert(() {
        print('${tag ?? key ?? child}:$constraints');
        return true;
      }());
      return child;
    });
  }
}
